<?php

abstract class Logger {
  private $debug = false;
  private $logger;

  public function debug($on_off = null){
    if(is_null($on_off)) return $this->debug;

    if($on_off) $this->debug = true;

    return $this;
  }

  protected function log($message){
    if(!$this->debug) return $this;

    $this->init_logger();

    $this->logger->log($message);

    return $this;
  }

  protected function error($message){
    if(!$this->debug) return $this;

    $this->init_logger();

    $this->logger->error($message);

    return $this;
  }

  public function inspect($label, $val = "__undefin_e_d__") {
    if(!$this->debug) return $this;

    Inspect::dummy();

    if($val == "__undefin_e_d__") {

      /* The first argument is not the label but the
               variable to inspect itself, so we need a label.
               Let's try to find out it's name by peeking at
               the source code.
      */
      $val = $label;

      $bt = debug_backtrace();
      $src = file($bt[0]["file"]);
      $line = $src[ $bt[0]['line'] - 1 ];

      // let's match the function call and the last closing bracket
      preg_match( "#Inspect::view\((.+)\)#", $line, $match );

      /* let's count brackets to see how many of them actually belongs
               to the var name
               Eg:   die(inspect($this->getUser()->hasCredential("delete")));
                      We want:   $this->getUser()->hasCredential("delete")
      */
      $max = strlen($match[1]);
      $varname = "";
      $c = 0;
      for($i = 0; $i < $max; $i++) {
        if(     $match[1]{$i} == "(" ) $c++;
        elseif( $match[1]{$i} == ")" ) $c--;
        if($c < 0) break;
        $varname .=  $match[1]{$i};
      }
      $label = $varname;
    }

    // now the actual function call to the inspector method,
    // passing the var name as the label:
    return dInspect::dump($label, $val, 7);
  }

  private function init_logger(){
    // si no hay un logger inicializa uno web por defecto
    if(empty($this->logger)) {
      $this->logger = new WebLog();
    }
  }

  public function logger($logger = null){
    if(!is_null($logger)) {
      $this->logger = $logger;
      return $this;
    }
  }
}